package com.xczz.service.impl;

import com.xczz.common.exception.CustomException;
import com.xczz.exception.BusinessException;
import com.xczz.model.SysRole;
import com.xczz.model.SysUser;
import com.xczz.model.vo.SysRoleVO;
import com.xczz.model.vo.SysUserVO;
import com.xczz.repository.SysRoleRepository;
import com.xczz.repository.SysUserRepository;
import com.xczz.repository.custom.SysRoleCustomRepository;
import com.xczz.service.SysRoleService;
import com.xczz.utils.BeanUtils;
import com.xczz.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.html.Option;
import java.util.*;

@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    public SysRoleRepository sysRoleRepository;
    @Transactional
    public int insertRole(SysRoleVO role){
        SysRole sysRole=new SysRole();
        BeanUtils.copyProperties(role,sysRole);
        sysRole.setDelFlag("0");
        sysRoleRepository.save(sysRole);
        role.setRoleId(sysRole.getRoleId());
        return insertRoleMenu(role);
    }
    @Transactional
    public int insertRoleMenu(SysRoleVO role){
        Long[] menus =role.getMenuIds();
        if(StringUtils.isNull(menus)||menus.length==0){
            return 0;
        }
        Long[] roles=new Long[menus.length];
        Arrays.fill(roles,role.getRoleId());
        return sysRoleRepository.batchInsertRoleMenu(roles,menus);
    }

    @Override
    @Transactional
    public boolean updateRole(SysRoleVO role){
        Long roleId=role.getRoleId();
        Optional<SysRole> op=sysRoleRepository.findById(roleId);
        if(!op.isPresent()){
            return false;
        }
        sysRoleRepository.deleteUserRoleByUserId(roleId);
        SysRole sysRole=op.get();
        BeanUtils.copyPropertiesIgnoreNull(role,sysRole);
        sysRoleRepository.save(sysRole);
        insertRoleMenu(role);
        return null!=sysRole.getRoleId();
    }

    @Transactional
    public int deleteRoleByIds(Long[] roleIds){
        for(Long roleId:roleIds){
            checkRoleAllowed(new SysRoleVO(roleId));
            SysRole role=selectRoleById(roleId);
            if(countUserRoleByRoleId(roleId)>0){
                throw new CustomException(String.format("%1$s已分配，不能删除",role.getRoleName()));
            }
            sysRoleRepository.deleteRoleMenuByRoleId(roleId);
        }
        return sysRoleRepository.deleteRoleByIds(roleIds);
    }

    public void checkRoleAllowed(SysRoleVO role){
        if(StringUtils.isNotNull(role.getRoleId())&&role.isAdmin()){
            throw new CustomException("不允许操作超级管理员角色");
        }
    }
    public SysRole selectRoleById(Long roleId){
        Optional<SysRole> op=sysRoleRepository.findById(roleId);
        return op.isPresent()?op.get():null;
    }
    public int countUserRoleByRoleId(Long roleId){
        return sysRoleRepository.countUserRoleByRoleId(roleId);
    }

    @Override
    public List<SysRole> selectRoleAll(){
        return sysRoleRepository.findAll();
    }

    @Override
    public List<SysRole> selectRoleListByUserId(Long userId){
        System.out.println(userId);
        System.out.println(sysRoleRepository.selectRoleIdsByUserId(userId));
        return sysRoleRepository.selectRoleIdsByUserId(userId);
    }
    public SysRole getRoleById(Long roleId) {
        return  sysRoleRepository.findById(roleId)
                .filter(role -> "0".equals(role.getDelFlag()))
                .orElse(null);
    }

    @Override
    public Set<String> selectRolePermissionByUserId(Long userId){
        List<SysRole> perms=sysRoleRepository.selectRoleIdsByUserId(userId);
        Set<String> permsSet=new HashSet<>();
        for(SysRole perm:perms){
            if(StringUtils.isNotNull(perm)){
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }
}
